<?php
namespace App\Api\Controllers;
use App\Admin\Models\Version;
use Common\ApiController;
use Common\Common;
use Common\Models\Activity;
use Common\Models\AppConfig;
use Common\Models\BShopAddress;
use Common\Models\BShopCityRegion;
use Common\Models\InvitecodeShares;
use Common\Models\OrderCommissions;
use Common\Models\User;
use Common\Models\Wallets;
use Common\Models\Withdrawals;
use Services\Api\SelfCenterServices;

class SelfCenterController extends ApiController
{
    public function initialize()
    {
        parent::initialize();
    }


    /**
     * 获取用户基本信息
     */
    public function get_userAction(){
        $user_data = Common::get_username_phone($this->user_info['id']);
        $this->ok($user_data);
    }


    //用户个人中心和个人收益合并
    public function get_userinfoAction(){
        $user_data = Common::get_username_phone($this->user_info['id']);
        $user_data['income'] = $this->income();
        if($user_data){
            $this->ok($user_data);
        }else{
            $this->fail(-1,'操作失败');
        }
    }



    //用户个人中心和个人收益合并
    public function userinfoAction(){
        $user = new User();
        $user_data = $user->find_by_id($this->user_info['id']);
        if($user_data){
            $this->ok($user_data);
        }else{
            $this->fail(-1,'操作失败');
        }
    }


    /**
     * 设置用户标签
     */
    public function tag_listAction(){
        $selfCenterServices = new SelfCenterServices();
        $data = $selfCenterServices->tagList();
        $this->ok($data);
    }


    //用户收益接口
    private function income(){
        $wallets = new Wallets();
        $user_wallerts = $wallets->findbyUserId((int)$this->params['user_id']);
        if(empty($user_wallerts)){
            $data['amount']="0.00";  //钱包余额
        }else {
            $data['amount'] = $user_wallerts->amount ? Common::number_randtwo($user_wallerts->amount) : "0.00";  //钱包余额
        }
        $start_end_time = Common::timeChange(1);  //今日的收益
        $today = $this->statisticsCount((int)$this->user_info['id'],$start_end_time,'today');
        $data['today']['estimate'] = $today['estimate'];                //预估收益

        $start_end_time = Common::timeChange(2);  //昨日的收益;
        $yestoday = $this->statisticsCount((int)$this->user_info['id'],$start_end_time,'yesterday');
        $data['yesterday']['estimate'] = $yestoday['estimate'];

        $start_end_time = Common::timeChange(8);  //本月的收益
        $month = $this->statisticsCount((int)$this->user_info['id'],$start_end_time,'month');
        $data['month']['estimate'] = $month['estimate'];

        $start_end_time = Common::timeChange(10);  //前天
        $upyestaday = $this->statisticsCount((int)$this->user_info['id'],$start_end_time,'upyestaday');

        $start_end_time = Common::timeChange(9);  //上月
		$upmonth = $this->statisticsCount((int)$this->user_info['id'],$start_end_time,'lastmonth');
		$data['lastmonth']['estimate'] = $upmonth['estimate'];
		$data['lastmonth']['icontrend'] = 1;

        //控制小图标显示
        $today['estimate'] - $yestoday['estimate'] >= 0 ? $data['today']['icontrend'] = 1 : $data['today']['icontrend'] = 0;
        $yestoday['estimate'] - $upyestaday['estimate'] >= 0 ? $data['yesterday']['icontrend'] = 1 : $data['yesterday']['icontrend'] = 0;
        $month['estimate'] - $upmonth['estimate'] >= 0 ? $data['month']['icontrend'] = 1 : $data['month']['icontrend'] = 0;
        return $data;
    }


    /**
     * @func 我的收益
     * @param time_type 1 今日 2 昨日 3 七天 4 15天 5 30天 6 60天 7 90天 8 本月 9 上月
     * @func 获取个人资料包含头像，登记，收益
     */
    public function get_infoAction(){
        $wallets = new Wallets();
        $user_wallerts = $wallets->findbyUserId((int)$this->user_info['id']);
        if(empty($user_wallerts)){
            $data['amount']="0.00";      //可提现
            $data['settled']="0.00";    //累计到账
            $data['withdrawed']="0.00";  //已提现
        }else{
            $data['amount']=$user_wallerts->amount;      //可提现

            $orderCommission = new OrderCommissions();
            $settled_time_end['start_at']="2019-10-01 00:00:00";
            $settled_time_end['end_at']="2222-10-01 00:00:00";
            $data['settled']=round($orderCommission->getOrderSettlementCommission($this->user_info['id'],$settled_time_end),2).'';

            $withdrawed = new Withdrawals();
            $data['withdrawed']=$withdrawed->get_withdrawal_all($this->user_info['id']);  //已提现
        }
        $orderCommission = new OrderCommissions();
        $data['unsettled']=$orderCommission->sum_money((int)$this->user_info['id']);   //未结清
		$data['order_all']=$orderCommission->order_all((int)$this->user_info['id']);
        $data['settlement_all'] = round($orderCommission->getOrderSettlementCommission($this->user_info['id'],$settled_time_end),2);
        $start_end_time = Common::timeChange(1);  //今日的收益
        $data['today'] = $this->statisticsCount((int)$this->user_info['id'],$start_end_time,'today');

        $start_end_time = Common::timeChange(2);  //昨日的收益
        $data['yesterday'] = $this->statisticsCount((int)$this->user_info['id'],$start_end_time,'yesterday');

        $start_end_time = Common::timeChange(8);  //本月的收益
        $data['month'] = $this->statisticsCount((int)$this->user_info['id'],$start_end_time,'month');
        $start_end_time = Common::timeChange(9);  //上月的收益
        $data['lastmonth'] = $this->statisticsCount((int)$this->user_info['id'],$start_end_time,'lastmonth');
		$data['unsettled']=Common::number_randtwo($data['unsettled']);
		$data['all_pre']=Common::number_randtwo($data['all_pre']);
		$data['settlement_all']=Common::number_randtwo($data['settlement_all']);
        $this->ok($data);
    }



    /**
     * @func 新的我的收益
     * @param time_type 1 今日 2 昨日 3 七天 4 15天 5 30天 6 60天 7 90天 8 本月 9 上月
     * @func 获取个人资料包含头像，登记，收益
     */
    public function get_infonewAction(){
        $selfCenterServices = new SelfCenterServices();
        $data = $selfCenterServices->getInfoNew($this->user_info);
        $this->ok($data);
    }


    /**
     * @func 获取统计数据
     * @param $user_id 用户id
     * @param $start_end_time 时间节点
     * @param $flag 日期标识
     */
    public function statisticsCount($user_id,$start_end_time,$flag=''){
        $orderCommission = new OrderCommissions();
        $self_count = $orderCommission->getOrderCount($user_id,$start_end_time);        //自购订单数
        $selftaobaoCount=isset($self_count['haodanku']) ? $self_count['haodanku'] : 0;      //自己淘宝的订单数
        $selfjdCount=isset($self_count['jd']) ? $self_count['jd'] : 0;                  //自己京东的订单数
        $selfpddCount=isset($self_count['pdd']) ? $self_count['pdd'] : 0;   //自己拼多多的订单数

        //粉丝订单数量
        $fans_count = $orderCommission->getFansOrderCounts($user_id,$start_end_time);        //粉丝订单
        $fanstaobaoCount=isset($fans_count['haodanku']) ? $fans_count['haodanku'] : 0;  //粉丝淘宝订单
        $fansjdCount=isset($fans_count['jd']) ? $fans_count['jd'] : 0;
        $fanspddCount=isset($fans_count['pdd']) ? $fans_count['pdd'] : 0;
        //订单数量=自购+粉丝
        $data['orderCount']=$selftaobaoCount+$selfjdCount+$selfpddCount+$fanstaobaoCount+$fansjdCount+$fanspddCount;
        $data['taobao']['count']=$selftaobaoCount+$fanstaobaoCount;
        $data['jd']['count']=$selfjdCount+$fansjdCount;
        $data['pdd']['count']=$selfpddCount+$fanspddCount;
        //付款预估佣金
        $estimateMoney = $orderCommission->getOrderChannelEstimateCommission($user_id,$start_end_time);
        $taobaoEstimateMoney=isset($estimateMoney['haodanku']) ? $estimateMoney['haodanku'] : 0;
        $jdEstimateMoney=isset($estimateMoney['jd']) ? $estimateMoney['jd'] : 0;
        $pddEstimateMoney=isset($estimateMoney['pdd']) ? $estimateMoney['pdd'] : 0;
        $data['settlement']=Common::number_randtwo($taobaoEstimateMoney+$jdEstimateMoney+$pddEstimateMoney);                    //兼容旧版本的
        $data['new_estimate']=Common::number_randtwo($taobaoEstimateMoney+$jdEstimateMoney+$pddEstimateMoney);                    //新版本的
        $data['taobao']['money']=Common::number_randtwo($taobaoEstimateMoney);
        $data['jd']['money']=Common::number_randtwo($jdEstimateMoney);
        $data['pdd']['money']=Common::number_randtwo($pddEstimateMoney);
        $data['deatil'][]=['name'=>'淘宝','count'=>$data['taobao']['count'],'money'=> $data['taobao']['money']];
        $data['deatil'][]=['name'=>'京东','count'=>$data['jd']['count'],'money'=> $data['jd']['money']];
        $data['deatil'][]=['name'=>'拼多多','count'=>$data['pdd']['count'],'money'=> $data['pdd']['money']];
        //结算预估佣金
        $data['estimate']=Common::number_randtwo($orderCommission->getOrderSettlementCommission_new3($user_id,$start_end_time));     //兼容旧版本的
        $data['new_settlement'] = Common::number_randtwo($orderCommission->getOrderSettlementCommission($user_id,$start_end_time));     //新版本的

        return $data;
    }



    /**
     * 验证原来的手机号
     */
    public function validate_phoneAction(){
        $user = new User();
        $user_info = $user->find_by_firstId((int)$this->user_info['id']);
        if(!isset($this->params['phone']) || empty($this->params['phone'])){
            $this->fail(-1,'用户手机号码不能为空');
        }else{
            if(!preg_match("/^1[3456789]{1}\d{9}$/",$this->params['phone'])){
                $this->fail(-1,'用户手机号码错误');
            }
            if($user_info['phone'] != $this->params['phone']){
                $this->fail(-1,'对不起，您输入的手机号不是该账号绑定的手机号');
            }
        }

        if((!isset($this->params['verification_code']) || empty($this->params['verification_code']) && (!isset($this->params['msg_id']) || empty($this->params['msg_id'])))){
            $this->fail(-1,'验证码和短信id不能为空');
        }else {
            $check_smg=$this->jpush->jgcheckcode($this->params['msg_id'],$this->params['verification_code']);
            if(!$check_smg['code']){
                $this->fail(-1,$check_smg['msg']);
            }
        }
        $this->ok([]);
    }



    /**
     * 更换手机
     */
    public function update_phoneAction(){
        $user = new User();
        $user_info = $user->find_by_firstId((int)$this->user_info['id']);
        if(!isset($this->params['phone']) || empty($this->params['phone'])){
            $this->fail(-1,'用户手机号码不能为空');
        }else{

            if(!preg_match("/^1[3456789]{1}\d{9}$/",$this->params['phone'])){
                $this->fail(-1,'用户手机号码错误');
            }
            //查询手机号是否被使用
            $list=$user->find_by_phone($this->params['phone']);
            if(!empty($list)){
                $this->fail(-1,'手机号已被使用');
            }
            $user_info['phone']=$this->params['phone'];
        }

        $result = $user->save_user($user_info);
        if($result){
            $this->cache->del_cache("user_".$this->user_info['id']);
            $this->ok([]);
        }else{
            $this->fail(-1,'更改失败');
        }
    }

    /**
     * @func 修改个人资料
     */
    public function update_basic_infoAction(){
        $user = new User();
        $user_info = $user->find_by_firstId((int)$this->user_info['id']);
        if(isset($this->params['nickname']) && !empty($this->params['nickname'])){
            if(empty($user_info['nickname'])){
                //$user->growth_value(8,$this->user_info['id']);
            }

            $user_info['nickname'] = $this->params['nickname'];
        }
        if(isset($this->params['sex']) && !empty($this->params['sex'])){
            $user_info['gender'] = (int)$this->params['sex'];
            if($user_info['gender'] != 1 && $user_info['gender'] != 2){
                $this->fail(-1,'性别参数错误');
            }
        }
        if(isset($this->params['job']) && !empty($this->params['job'])){
            $user_info['job'] = $this->params['job'];
        }
        $result = $user->save_user($user_info);
        if($result){
            $this->cache->del_cache("user_".$this->user_info['id']);
            $this->ok([]);
        }else{
            $this->fail(-1,'更改失败');
        }
    }

    /**
     * @func 绑定支付宝信息
     */
    public function bind_alipayAction(){
        $user = new User();
        $user_info = $user->find_by_firstId((int)$this->user_info['id']);
        $alipay_account = $user_info['alipay_account'];
        if(!isset($this->params['alipay_account']) || empty($this->params['alipay_account'])){
            $this->fail(-1,'支付宝账号不能为空');
        }
        $user_info['alipay_account'] = $this->params['alipay_account'];

        if(!isset($this->params['real_name']) || empty($this->params['real_name'])){
            $this->fail(-1,'用户真实姓名不能为空');
        }
        $user_info['real_name'] = $this->params['real_name'];

        if(!isset($this->params['phone']) || empty($this->params['phone'])){
            $this->fail(-1,'用户手机号码不能为空');
        }else{
            if(!preg_match("/^1[3456789]{1}\d{9}$/",$this->params['phone'])){
                $this->fail(-1,'用户手机号码错误');
            }
        }
        if(!isset($this->params['verification_code']) || empty($this->params['verification_code'])){
            $this->fail(-1,'验证码不能为空');
        }else {
            if(isset($this->params['msg_id'])){//极光
                if(empty($this->params['msg_id'])){
                    $this->fail(-1,'短信id不能为空');
                }
                $check_smg=$this->jpush->jgcheckcode($this->params['msg_id'],$this->params['verification_code']);
                if(!$check_smg['code']){
                    $this->fail(-1,$check_smg['msg']);
                }
            }else{//阿里云
                $code_obj = new Codes();
                $find_code_phone = $code_obj->find_by_phone($this->params['phone']);
                if ($find_code_phone) {
                    if (strtotime($find_code_phone['expire_at']) < time()) {
                        $this->fail(-1, '验证码过期，请从新获取');
                    }
                    if ($find_code_phone['code'] != $this->params['verification_code']) {
                        $this->fail(-1, '验证码输入错误');
                    }
                }else{
                    $this->fail(-1, '请获取验证码');
                }
            }
        }
        $result = $user->save_user($user_info);
        if($result){
            if(!$alipay_account){
                //$user->growth_value(10,$this->user_info['id']);
            }
            $this->cache->del_cache("user_".$this->user_info['id']);
            $this->ok([]);
        }else{
            $this->fail(-1,'更改失败');
        }
    }

    /**
     * 绑定微信号
     */
    public function bind_weixinAction(){
        if(!isset($this->params['weixin_no']) || empty($this->params['weixin_no'])){
            $this->fail(-1,'微信账号不能为空');
        }
        $user = new User();
        $user_info = $user->find_by_firstId((int)$this->user_info['id']);
        $user_info['weixin_no']=$this->params['weixin_no'];
        $result = $user->save_user($user_info);
        if($result){
            $this->cache->del_cache("user_".$this->user_info['id']);
            $this->ok([]);
        }else{
            $this->fail(-1,'绑定失败');
        }
    }


	/*
	 解绑淘宝授权
	 */
	public function unbind_tbridAction(){
        $user = new User();
        $user_info = $user->find_by_id((int)$this->user_info['id']);
        if(!$user_info){
            $this->fail(-1,'解绑失败');
        }
        $user_info->tb_rid='';
        $user_info->save();
        if($user_info->id){
            $this->cache->del_cache("user_".$this->user_info['id']);
            $this->ok([]);
        }else{
            $this->fail(-1,'绑定失败');
        }

	}

    /**
     * @func 淘宝授权code码获取
     */
    public function taobao_authAction(){
        if (!empty($this->user_info['tb_rid']) && !empty($this->user_info['tb_special_id']) ){
            $responseResult = [
                'rid'=>$this->user_info['tb_rid'],
                'tb_special_id'=>$this->user_info['tb_special_id'],
                'url'=>''
            ];
            return $this->ok($responseResult,1,'您已经授权过了');
        }

        $result = $this->taobao->taobao_authorizes($this->user_info['id']);
        $responseResult = [
            'rid'=>empty($this->user_info['tb_rid']) ? '':$this->user_info['tb_rid'],
            'tb_special_id'=>$this->user_info['tb_special_id'],
            'url'=>$result
        ];
        return $this->ok($responseResult,1,'去授权吧');
    }


    /**
     * @func 分享邀请码
     */
    public function invite_shareAction(){
        $user_id = $this->params['user_id'];
        $user = new User();
        $user_info = $user->find_by_firstId($user_id);
        $invitecodeshares = new InvitecodeShares();
        $list=$invitecodeshares->inviteShare($user_info);
        return $this->ok($list);
    }


    /**
     * 设置头像
     */
    public function set_avatarAction(){
        if(!isset($this->params['avatar']) || empty($this->params['avatar'])){
            $this->fail(-1,'请设置头像');
        }
        $user = new User();
        $user_info = $user->find_by_id($this->params['user_id']);
        $user_info->avatar = $this->params['avatar'];
        $user_info->save();
        $this->cache->del_cache("user_".$this->user_info['id']);
        $this->ok([]);
    }




    /**
     * 关于我们
     */
    public function aboutusAction(){
        $systemset = new Systemset();
        $result = $systemset->find_bu_first();
        if($result){
            $this->ok($result);
        }else{
            $this->fail(-200,'列表没有消息');
        }
    }




    /**
     * 反馈
     */
    public function feedbacksAction(){
        if(!isset($this->params['content']) || empty($this->params['content'])){
            $this->fail(-1,'反馈内容不能为空');
        }
        $data['content'] = $this->params['content'];
        if(!isset($this->params['contact']) || empty($this->params['contact'])){
            $this->fail(-1,'联系方式不能为空');
        }
        $data['contact'] = $this->params['contact'];
        $data['user_id'] = $this->user_info['id'];
        $data['created_at'] = date('Y-m-d H:i:s',time());
        $data['feedback_category_id'] =1;
        $feedbacks = new Feedbacks();
        $result = $feedbacks->save($data);
        if($result){
            $this->ok();
        }else{
            $this->fail(-1,'反馈失败');
        }

    }


    //联系导师
    public function myteacherAction(){
        if($this->user_info['weixin_no']){
            $result['weixin_no'] = $this->user_info['weixin_no'];
            $result['avatar'] = $this->user_info['avatar'];
        }else{
            $result['weixin_no']='buygou9991';
            $result['avatar']='';
        }
        $this->ok($result);
    }


    /**
     * 版本推送
     */
    public function versionAction(){
        $source = $this->params['source'];
        $version = new Version();
        $list = $version->find_by_newVersion($source);
        if(!empty($list)){
            $list = Common::transition_array($list);
            $this->ok($list);
        }
        $this->fail(-1,'已经是最新版');
    }


    /**
     * 版本推送
     */
    public function version_newAction(){
//        if(!isset($this->params['u_version']) || empty($this->params['u_version'])){
//            $this->fail(-1,'没有版本号');
//        }
//        if(!isset($this->params['os']) || empty($this->params['os'])){
//            $this->fail(-1,'没有平台');
//        }
//        $version = new Version();
//        $list = $version->find_by_newVersion_new($this->params['u_version'],$this->params['os']);
//        if($list){
//            $list['forceUpdate'] = $list['forceUpdate']==1 ? true : false;
//            $this->ok($list);
//        }
        $this->fail(-1,'已经是最新版');
    }






    /**
     * 专属口令
     */
    public function exclusive_codeAction(){
        $user = new User();
        $data['start_end_time']=0;
        $count = $user->getDirectFansCount($this->user_info['id'],$data);
        $invite_code = $this->user_info['exclusive_code']?$this->user_info['exclusive_code']:$this->user_info['invite_code'];
        if($this->request->isGet()){
            $this->ok(['count'=>$count,'exclusive_code'=>$invite_code,'is_exclusive'=>$this->user_info['exclusive_code']?1:0]);
        } else {
            $exclusive_code = $this->params['exclusive_code'];
            if($count < 3){
                $this->fail(-1,'直邀人数少于3人!');
            }
            //$pattern = '/^[0-9]{6,8}$/';
            $pattern = '/^(?![^a-zA-Z]+$)(?!\D+$).{6,8}$/';
            if(!preg_match($pattern,$exclusive_code)){
                $this->fail(-1,'口令必须包含数字字母长度6-8位');
            }
            $model = $user->find_by_id($this->user_info['id']);
            if($model->exclusive_code){
                $this->fail(-1,'您已经设置了专属口令');
            }
            $is_exclusive = $user->find_by_phone_info($exclusive_code);
            if($is_exclusive){
                $this->fail(-1,'该口令已经被占用');
            }
            $model->exclusive_code = strtoupper($exclusive_code);
            $model->is_exclusive = 1;
            if($model->save()){
                $this->ok('设置成功!');
            }
            $this->fail(-1,'设置失败!');
        }
    }



    /**
     * 微信解绑
     */
    public function untying_weixinAction(){
        $user = new User();
        $user_info = $user->find_by_id($this->params['user_id']);
        if(!$user_info){
            $this->fail(-1,'没有找到用户');
        }
        $user_info->wx_account='';
        $result = $user_info->save();
        if($result){
            $this->cache->del_cache("user_".$this->user_info['id']);
            $this->ok([]);
        }else{
            $this->fail(-1,'解绑失败');
        }
    }

    /**
     * 设置密码
     */
    public function set_passwordAction(){
        $user = new User();
        $user_info = $user->find_by_id($this->params['user_id']);
        if ((!isset($this->params['smscode']) || empty($this->params['smscode'])) && (!isset($this->params['msg_id']) || empty($this->params['msg_id'])) ) {
            $this->fail(-1, '验证码不能为空');
        }
        if (!isset($this->params['pwd']) || empty($this->params['pwd'])) {
            $this->fail(-1, '密码不能为空');
        }else{
            $pattern= '/^[0-9a-z_$]{6,16}$/i'; // i 不区分大小写
            if(!preg_match($pattern,$this->params['pwd'])){
                $this->fail(-1,'密码只能是数字加字母，长度6-16位');
            }
        }
        $pwd = md5(md5($this->params['pwd']));
        if(md5(md5($this->params['repwd'])) != $pwd ){
            $this->fail(-1,'两次密码输入不一致');
        }

        $check_smg=$this->jpush->jgcheckcode($this->params['msg_id'],$this->params['smscode']);
        if(!$check_smg['code']){
            $this->fail(-1,$check_smg['msg']);
        }

//        $code_obj = new Codes();
//        $find_code_phone = $code_obj->find_by_phone($this->params['phone']);
//        if ($find_code_phone) {
//            if (strtotime($find_code_phone['expire_at']) < time()) {
//                $this->fail(-1, '验证码过期，请从新获取');
//            }
//            if ($find_code_phone['code'] != $this->params['smscode']) {
//                $this->fail(-1, '验证码输入错误');
//            }
//        } else {
//            $this->fail(-1, '请获取验证码');
//        }
        $user_info->password=$pwd;
        $result = $user_info->save();
        if($result){
            $this->ok([]);
        }else{
            $this->fail(-1,'密码设置失败');
        }
    }

    /**
     * 设置隐私
     * type 0 隐私开关 1消息开关
     * switch 0关闭  1开启
     */
    public function set_privacy_switchAction(){
       // $type = $this->params['type']?$this->params['type']:0;
        $switch = $this->params['switch']?$this->params['switch']:0;
        $user = new User();
        $user = $user->find_by_id($this->user_info['id']);
        $user->is_privacy = $switch;
        $user->updated_at = date('Y-m-d H:i:s');
        if($user->save()){
            $this->ok('设置成功!');
        }
        $this->fail(-1, '设置失败!');
    }



    /**
     * 外卖劵
     * type 1 饿了么 2小程序 3口碑 4饿了么果蔬
     */
    public function waimaijuanAction(){
        $relationid = $this->user_info['tb_rid']?$this->user_info['tb_rid']:'';
        if(empty($relationid)){
            $this->fail(-1, '请先设置淘宝授权!');
        }
        $data['url']='';
        $data['path']='';
        $id = 1571715733668;
        $res = $this->taobao->activitylink_new($id,$relationid);
        if($res['code']){
            $data['path']='http://qn.enshitc.com/waimai/elm.png';
            $data['url'] = $res['data'];
        }
        $result[0]=Common::router('饿了么优惠券',$data['path'],3,'AwakeTbApp',$data['url'],1);

        $id = 1583739244161;
        $res = $this->taobao->activitylink_new($id,$relationid);
        if($res['code']){
            $data['path']="http://qn.enshitc.com/waimai/koubei.png";
            $data['url']=$res['data'];
        }
        $result[1]=Common::router('口碑',$data['path'],3,'AwakeTbApp',$data['url'],1);

        $id = 1585018034441;
        $res = $this->taobao->activitylink_new($id,$relationid);
        if($res['code']){
            $data['path']="http://qn.enshitc.com/waimai/elemgs.png";
            $data['url']=$res['data'];
        }
        $result[2]=Common::router('买菜到家优惠券',$data['path'],3,'AwakeTbApp',$data['url'],1);


        $data['path']='http://qn.enshitc.com/waimai/meituan.png';
        $data['url'] = "https://c.duomai.com/track.php?site_id={$this->di->getConfig()->services->duomai->duomai_id}&aid=10130&euid={$this->user_info['id']}&t=https%3A%2F%2Fi.meituan.com&dm_fid=16052";
        $result[3]=Common::router('美团优惠券',$data['path'],2,'H5UserId',$data['url'],0);


        $data['path']='https://jzcloud.jiruan.ltd/1626409896606';
        $data['url'] = "https://c.duomai.com/track.php?site_id={$this->di->getConfig()->services->duomai->duomai_id}&aid=5933&euid={$this->user_info['id']}&t=https%3A%2F%2Fkfc.qianzhu8.com%2Findex%3F&dm_fid=16052";
        $result[4]=Common::router('肯德基',$data['path'],2,'H5UserId',$data['url'],0);

        $this->ok($result);
    }




    /**
     * 获取活动转链
     */
    public function activityAction()
    {
        $id = $this->params['id'];
        if (!isset($id) || empty($id)) {
            $this->fail(-1, '缺少参数!');
        }
        $relationid = $this->user_info['tb_rid'] ? $this->user_info['tb_rid'] : '';
        if (empty($relationid)) {
            $this->fail(-1, '请先设置淘宝授权!');
        }
        $db = new Activity();

        $where['conditions'] = "id = $id and is_del = 1";
        $info                = $db->findFirst($where);
        if (empty($info)) {
            $this->fail(-1, '未找到!');
        }

        $info                       = $info->toarray();
        $res['share_img']           = $info['share_img'];
        $res['type']                = $info['type'];
        $res['poster']              = $info['poster'];
        $res['bnt_colour']          = $info['bnt_colour'];//颜色
        $res['bnt_colour_gradient'] = $info['bnt_colour_gradient'];//颜色
        $res['bot_colour']          = $info['bot_colour'];//颜色
        $res['text_color']          = $info['text_color'];//颜色
        $res['copy_btn_color'] = $info['copy_btn_color'];//颜色
        $res['copy_text_color']          = $info['copy_text_color'];//颜色
        $res['url']                 = '';//显示的url
        $res['h5_url']              = '';//传给原生的二维码
        $res['token']               = '';//口令
        $res['zhuan_url']           = '';//拉起app
        $res['dec']                 = $info['dec'];
        $res['page_bgcolor']                 = $info['page_bgcolor'];
        $appconfig                  = new AppConfig();
        $app_config                 = $appconfig->find_list('h5goodsdetail_url');
        switch ($info['type']) {
            case 1://淘宝
                $url = $this->taobao->activitylink_new($info['activity_id'], $relationid);
                if ($url['status']) {
                    $res['url']    = $url['data']['url'] ? $url['data']['url'] : '';
                    $temp['title'] = $info['title'];
                    $temp['url']   = $url['data']['url'];
                    $temp['image'] = $info['poster'];
                    $datas         = $this->taobao->couponUrlToText($temp);
                    if ($datas['code'] == 1) {
                        $model_str   = $datas['model'];
                        $model       = $datas['model'];
                        $pattern     = "/[\x7f-\xff]/sim";
                        $replacement = '';
                        $model_str   = preg_replace($pattern, $replacement, $model);
                        $model_arr   = explode('￥', $model);
                        if ($model_arr && isset($model_arr[1])) {
                            $model_str = str_ireplace($model_arr[1], "￥{$model_arr[1]}￥", $model_str);
                            $model_str = '0复制文本' . substr($model_str, strpos($model_str, '￥'));
                        }

                        $h5_url           = $app_config['h5goodsdetail_url'] . '?kouling=' . base64_encode($model_str) . '&img=' . urlencode($info['poster']) . '&type=' . urlencode('taobao');
                        $res['h5_url']    = $h5_url;
                        $res['token']     = $datas['model'];
                        $res['url']       = $datas['model'];
                        $res['zhuan_url'] = $url['data'];
                    } else {
                        $this->fail(-1, '获取失败!');
                    }
                } else {
                    $this->fail(-1, '该活动已下架或者非淘宝客活动');
                }
                break;
            case 2://京东
                $url = $this->jd->activity_createturn($this->user_info['id'], $info['activity_id']);

                if ($url['status'] === true) {
                    $res['token']     = $url['short_url'];
                    $res['zhuan_url'] = $url['short_url'];
                    $h5_url           = $app_config['koubei'] . '?kouling=' . base64_encode($url['short_url']) . '&img=' . urlencode($info['poster']) . '&type=' . urlencode('jd');
                    $res['h5_url']    = $url['short_url'];
                    $res['url']       = $url['short_url'];
                } else {
                    $this->fail(-1, '获取失败!');
                }
                break;
            case 3://拼多多

                if (empty($this->user_info['pdd_pid'])) {
                    $response_pdd = $this->pdd->Createppdid($this->user_info['phone']);
                    $user         = new User();
                    $user_arr     = $user->find_by_phone($this->user_info['phone']);
                    if ($response_pdd['code']) {
                        $user_arr['pdd_pid'] = $response_pdd['msg'];
                        $result              = $user->save_user($user_arr);
                        if ($result) {
                            $this->user_info['pdd_pid'] = $user_arr['pdd_pid'];
                            $this->cache->del_cache("user_" . $this->user_info['id']);
                        } else {
                            $this->fail(-1, '获取拼多多授权失败');
                        }
                    } else {
                        $str_phone    = $this->user_info['phone'];
                        $response_pdd = $this->pdd->Createppdid($str_phone . rand(1, 1000));
                        if ($response_pdd['code']) {
                            $user_arr['pdd_pid'] = $response_pdd['msg'];
                            $result              = $user->save_user($user_arr);
                            if ($result) {
                                $this->user_info['pdd_pid'] = $user_arr['pdd_pid'];
                                $this->cache->del_cache("user_" . $this->user_info['id']);
                            } else {
                                $this->fail(-1, '获取拼多多授权失败');
                            }
                        }
                    }
                }

                $params['url'] = trim($info['activity_id']);
                $url           = $this->pdd->site_turn($this->user_info['pdd_pid'], $params);
                if (!$url['code']) {
                    $this->fail(-1, '转链失败!');
                }
                //$h5_url           = $app_config['koubei'] . '?kouling=' . base64_encode($url['data']['we_app_web_view_short_url']) . '&img=' . urlencode($info['poster']) . '&type=' . urlencode('pdd');
                $res['token']     = $url['data']['we_app_web_view_short_url'];//微信
                $res['zhuan_url'] = $url['data']['url'];//立即进入 $url['data']['url'];
                $res['h5_url']    = $url['data']['mobile_short_url'];//$url['data']['url'];//$url['data']['we_app_web_view_short_url'];
                $res['url']       = $url['data']['short_url'];//$url['data']['url'];//$url['data']['short_url'];//立即进入
                break;
        }
        if (!empty($res['dec'])) {
            if (!empty($res['token'])) {
                $str         = explode('|', $info['dec']);
                $token_model = isset($res['token']['model']) ? $res['token']['model'] : $res['token'];
                $res['dec']  = $str[0] . $token_model . $str[1];
            }
        }


        $this->ok($res);
    }





    /**
     * 通用分享：TODO
     * type 1 饿了么 2小程序 3口碑 4饿了么果蔬
     * id 转链对象ID
     */
    public function currency_shareAction(){
        $type = $this->params['type']?$this->params['type']:0;
//        $id = $this->params['id']?$this->params['id']:0;
        $res['poster'] = 'http://jzcloud.jiruan.ltd/img/hb/xcxhb.png';
        $res['url'] = '';
        $res['h5_url'] = 'https://www.baidu.com/';

        $relationid = $this->user_info['tb_rid']?$this->user_info['tb_rid']:'';
        switch ($type){
            case 1:
                if(empty($relationid)){
                    $this->fail(-1, '请先设置淘宝授权!');
                }
                $id = 1571715733668;
                $url = $this->taobao->activitylink_new($id,$relationid);
                if($url['code']){
                    $res['url'] = $url['wx_img'];
                    $temp['title'] = '饿了么';
                    $temp['url'] = $url['data'];
                    $temp['image'] = 'http://jzcloud.jiruan.ltd/img/hb/bwc3.png';
                    $datas = $this->taobao->couponUrlToText($temp);
                    if($datas['code'] == 1) {
                        $res['token'] = $datas['data'];
                        $res['zhuan_url'] = $url['data'];
                    } else {
                        $this->fail(-1, '获取失败!');
                    }
                    $res['poster'] = 'http://jzcloud.jiruan.ltd/img/hb/bwc3.png';
                }
            break;
            case 2:
                $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
                $puth = "/img/qrcode/".$this->user_info['id'].'.png';
                if(file_exists('./'.$puth)){
                    $res['url'] = $http_type.$_SERVER['HTTP_HOST'] .$puth;
                } else {
                    $redis_key = "getaccesstoken";
                    $accesstoken = $this->cache->get_cache($redis_key);
                    if (!$accesstoken) {
                        $result_accesstoken = $this->xcx->getaccesstoken();
                        if (!$result_accesstoken['code']) {
                            $this->fail(-1, $result_accesstoken['msg']);
                        }
                        $accesstoken = $result_accesstoken['data'];
                        $this->cache->set_cache($redis_key, $accesstoken, 7000);
                    }
                    $h_params['scene'] = $this->user_info['invite_code'];
                    $h_params['page'] = 'pages/home/home';
                    $result = $this->xcx->getcode($h_params, $accesstoken);
                    if ($result['code']) {
                        file_put_contents('./'.$puth, $result['msg']);
                        $res['url'] = $http_type.$_SERVER['HTTP_HOST'] .$puth;
                    }
                }
            break;
            case 3://口碑
                if(empty($relationid)){
                    $this->fail(-1, '请先设置淘宝授权!');
                }
                $id = 1583739244161;
                $url = $this->taobao->activitylink_new($id,$relationid);
                if($url['code']){
                    $res['url'] = $url['wx_img']?$url['wx_img']:'';
                    $temp['title'] = '口碑';
                    $temp['url'] = $url['data'];
                    $temp['image'] = 'http://jzcloud.jiruan.ltd/img/hb/koubeib3.png';
                    $datas = $this->taobao->couponUrlToText($temp);
                    if($datas['code'] == 1) {
                        $appconfig = new AppConfig();
                        $app_config = $appconfig->find_list('koubei');
                        $h5_url = 'https://juzhe.kuaizhan.com/29/72/p709484265b1748?kouling='.urlencode($datas['data']);
                        if(isset($app_config['koubei']) && !empty($app_config['koubei'])){
                            $h5_url = $app_config['koubei'].'?kouling='.urlencode($datas['data']);
                        }
                        $res['h5_url'] = $h5_url;
                        $res['token'] = $datas['data'];
                        $res['zhuan_url'] = $url['data'];
                    } else {
                        $this->fail(-1, '获取失败!');
                    }
                    $res['poster'] = 'http://jzcloud.jiruan.ltd/img/hb/koubei3.png';
                }
                break;
            case 4://饿了么果蔬
                if(empty($relationid)){
                    $this->fail(-1, '请先设置淘宝授权!');
                }
                $id = 1585018034441;
                $url = $this->taobao->activitylink_new($id,$relationid);
                if($url['code']){
                    $res['zhuan_url'] = $url['data'];
                    $res['short_click_url'] = $url['short_click_url'];
                    $res['url'] = $url['wx_img'];
                    $temp['title'] = '饿了么果蔬';
                    $temp['url'] = $url['data'];
                    $temp['image'] = 'http://jzcloud.jiruan.ltd/img/hb/elnhb3.png';
                    $datas = $this->taobao->couponUrlToText($temp);
                    if($datas['code'] == 1) {
                        $res['token'] = $datas['data'];
                    } else {
                        $this->fail(-1, '获取失败!');
                    }
                    $res['poster'] = 'http://jzcloud.jiruan.ltd/img/hb/elnhb3.png';
                }
                break;
        }
        $this->ok($res);
    }


    /**
     * 注销
     */
    public function loginoutAction(){
        $user = new User();
        $user_obj = $user->find_by_id($this->params['user_id']);
        $user_obj->is_disable=1;
        $user_obj->save();
        $this->ok([]);
    }


    //获取七牛上传token
    public function getqiniutokenAction(){
        $token = $this->qiniu->get_token();
        $this->ok(['token'=>$token]);
    }



    /**
     * 我的收货地址列表
     */
    public function address_listAction(){
        $BShopAddressDb = new BShopAddress();
        $get_list = $BShopAddressDb->get_list($this->user_info['id']);
        $this->ok($get_list);
    }

    /**
     * 设为默认收货地址
     */
    public function default_set_addressAction(){
        if(!isset($this->params['address_id']) || empty($this->params['address_id'])){
            $this->fail(-1,'地址id不能为空');
        }
        $BShopAddressDb = new BShopAddress();
        $get_list = $BShopAddressDb->find(array(
            "conditions"=>"user_id={$this->user_info['id']}",
        ))->update(['is_default'=>0]);
        if($get_list){
            $find_one = $BShopAddressDb->findFirstById($this->params['address_id']);
            if($find_one){
                $find_one->is_default = 1;
                $find_one->updated_at = date('Y-m-d H:i:s');
                if($find_one->save()){
                    $this->ok([]);
                }
            }
        }
        $this->fail(-1,'修改失败');
    }


    /**
     * 获取用户默认的收货地址
     */
    public function get_address_infoAction(){
        if(!isset($this->params['address_id']) || empty($this->params['address_id'])){
            $conditions="user_id={$this->user_info['id']} AND is_default=1";
        }else{
            $conditions="id={$this->params['address_id']}";
        }

        $BShopAddressDb = new BShopAddress();
        $find_one = $BShopAddressDb->findFirst(array(
            "conditions"=>$conditions
        ));
        if(!$find_one){
            $this->ok([]);
        }
        $data['id'] = $find_one->id;
        $data['name'] = $find_one->name;
        $data['address'] = $find_one->province.$find_one->city.$find_one->area.$find_one->address;
        $data['phone']=$find_one->phone;
        $this->ok($data);
    }

    /**
     * 删除地址
     */
    public function del_addressAction(){
        if(!isset($this->params['address_id']) || empty($this->params['address_id'])){
            $this->fail(-1,"请选择地址");
        }
        $BShopAddressDb = new BShopAddress();
        $find_one = $BShopAddressDb->findFirstById($this->params['address_id']);
        if(!$find_one){
            $this->fail(-1,'没有找到记录');
        }
        if($find_one->delete()){
            $this->ok([]);
        }
        $this->fail(-1,'删除失败');
    }


    /**
     * 获取详细地址
     */
    public function address_detailAction(){
        if(!isset($this->params['address_id']) || empty($this->params['address_id'])){
            $this->fail(-1,"地址id不能为空");
        }
        $BShopAddressDb = new BShopAddress();
        $shop_address = $BShopAddressDb->findFirstById($this->params['address_id']);
        if(!$shop_address){
            $this->fail(-1,'没有找到地址');
        }
        $this->ok($shop_address);
    }



    /**
     * 添加收货地址
     */
    public function add_addressAction(){
        if(!isset($this->params['name']) || empty($this->params['name'])){
            $this->fail(-1,"收货人不能为空");
        }
        if(!isset($this->params['phone']) || empty($this->params['phone'])){
            $this->fail(-1,"收货人电话不能为空");
        }

        $BShopCityReginDb = new BShopCityRegion();
        if(!isset($this->params['province_code']) || empty($this->params['province_code'])){
            $this->fail(-1,"请选择地址");
        }
        $prevince_find_one = $BShopCityReginDb->findFirstById($this->params['province_code']);
        if(!$prevince_find_one){
            $this->fail(-1,'地址错误,没有找到区域!');
        }
        if(!isset($this->params['city_code']) || empty($this->params['city_code'])){
            $this->fail(-1,"请选择地址");
        }
        $city_find_one = $BShopCityReginDb->findFirstById($this->params['city_code']);
        if(!$prevince_find_one){
            $this->fail(-1,'地址错误,没有找到区域!');
        }
        if(!isset($this->params['area_code']) || empty($this->params['area_code'])){
            $this->fail(-1,"请选择地址");
        }
        $area_find_one = $BShopCityReginDb->findFirstById($this->params['area_code']);
        if(!$prevince_find_one){
            $this->fail(-1,'地址错误,没有找到区域!');
        }
        if(!isset($this->params['address']) || empty($this->params['address'])){
            $this->fail(-1,"详细地址");
        }
        $BShopAddressDb = new BShopAddress();
        $find_one = $BShopAddressDb->findFirstById($this->params['address_id']);
        if($find_one){
            $find_one->name = $this->params['name'];
            $find_one->phone = $this->params['phone'];
            $find_one->province = $prevince_find_one->name;
            $find_one->province_code = $prevince_find_one->id;
            $find_one->city = $city_find_one->name;
            $find_one->city_code = $city_find_one->id;
            $find_one->area = $area_find_one->name;
            $find_one->area_code = $area_find_one->id;
            $find_one->address = $this->params['address'];
            $find_one->updated_at = date('Y-m-d H:i:s');
            if(!$find_one->save()){
                $this->fail(-1,'地址修改失败');
            }
        }else{
            $BShopAddressDb = new BShopAddress();
            $BShopAddressDb->user_id = $this->user_info['id'];
            $BShopAddressDb->name = $this->params['name'];
            $BShopAddressDb->phone = $this->params['phone'];
            $BShopAddressDb->province = $prevince_find_one->name;
            $BShopAddressDb->province_code = $prevince_find_one->id;
            $BShopAddressDb->city = $city_find_one->name;
            $BShopAddressDb->city_code = $city_find_one->id;
            $BShopAddressDb->area = $area_find_one->name;
            $BShopAddressDb->area_code = $area_find_one->id;
            $BShopAddressDb->address = $this->params['address'];
            $BShopAddressDb->is_default = 0;
            $BShopAddressDb->created_at = date('Y-m-d H:i:s');
            $BShopAddressDb->updated_at = date('Y-m-d H:i:s');
            if(!$BShopAddressDb->save()){
                $this->fail(-1,'地址添加失败');
            }
        }
        $this->ok([]);

    }

}
